<?php
/**
 * 微信小程序控制器
 */

namespace app\api\controller;


use app\common\bean\StoreUserBean;
use app\common\controller\ApiController;
use app\common\model\StoreUserModel;

class AppletWechat extends ApiController
{
    public function index(){
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch($RX_TYPE){
                case 'event':
                    if($postObj->Event=='CLICK'){
                        $resultStr = $this->handleClick($postObj);
                    }

                break;
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $resultStr;
        }
    }
    private function handleClick($object){
        if($object->EventKey=='kefu'){
            $contentStr = '客服电话13415713064';
        }

        return $this->responseText($object, $contentStr);
    }
    private function handleText($object){
        if(preg_match("/^1[345678]{1}\d{9}$/",$object->Content)){
            if($storeUser = StoreUserModel::getInstance()->where([StoreUserBean::$phone=>$object->Content])->find()){
                if($storeUser[StoreUserBean::$publicOpenId]){
                    $contentStr = '该手机号已经绑定微信';
                }else{
                    $data[StoreUserBean::$id] = $storeUser[StoreUserBean::$id];
                    $data[StoreUserBean::$publicOpenId] = $object->FromUserName;
                    StoreUserModel::getInstance()->update($data);
                    $contentStr = '手机号码绑定成功';
                }
            }else{
                $contentStr = "该手机未入驻";
            }

            return $this->responseText($object, $contentStr);
        }

    }
    private function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }
}